package ripplecraft.ripple_rescue.listener;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import ripplecraft.ripple_rescue.bean.MyPlayer;
import ripplecraft.ripple_rescue.util.Message;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class PlayerListener implements Listener {
    //当玩家死亡时，给予死亡惩罚
    @EventHandler
    public void respawn(PlayerRespawnEvent event) {
        Timer timer = new Timer();
        final boolean[] ok = {false};
        TimerTask timerTask = new TimerTask() {
            private Player player;
            @Override
            public void run() {
                if (!ok[0]) {
                    player = event.getPlayer();
                    player.setFoodLevel(8);
                    player.setHealth(player.getMaxHealth() / 6);
                    ok[0] = true;
                    player.sendMessage(ChatColor.YELLOW + "你受了重伤，需要调养。");
                }else {
                    timer.cancel();
                }
            }
        };
        timer.schedule(timerTask,1,1);
    }

    //当监听到一个玩家进入游戏时，将玩家信息保存至（或更新）json文件
    @EventHandler(priority = EventPriority.HIGH)
    public void onPlayerEnterGame(PlayerJoinEvent event) {
        MyPlayer myPlayer = new MyPlayer(event.getPlayer());
//        try {
//            if(new MyPlayer(event.getPlayer()).getInJsonFile(event.getPlayer().getUniqueId())==null){
//                MyPlayer myPlayer = new MyPlayer(event.getPlayer());
//                try {
//                    myPlayer.saveToJsonFile();
//                    event.getPlayer().sendMessage(ChatColor.GREEN + "成功创建新玩家数据");
//                } catch (IOException e) {
//                    Message.error(e.getMessage());
//                }
//            }else{
//                event.getPlayer().sendMessage(ChatColor.RED + "这个玩家已经存在啦！");
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }
}
